package fileListening

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

// 定义userError类型
type userError string

// string 也可以作为接口接收参数
func (e userError) Error() string { // userError接口实现
	return e.Message() // string也能实现一个接口
}

func (e userError) Message() string {
	return string(e)
}

const prefix = "/list/"

// 修改函数返回error
func HandleFileList(writer http.ResponseWriter, request *http.Request) error {
	if strings.Index(
		request.URL.Path, prefix) != 0 {
		return userError(
			fmt.Sprintf("path %s must start "+
				"with %s",
				request.URL.Path, prefix))
	}
	path := request.URL.Path[len(prefix):] // list/fib.txt  slice 去掉前面的list/，拿到真实路径
	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()
	bytes, err := ioutil.ReadAll(file)
	if err != nil {
		return err
	}

	writer.Write(bytes) // 内容写入 ResponseWriter
	return nil
}
